package cn.bijy.config;

import cn.bijy.pojo.Configuration;
import cn.bijy.pojo.MapedStatement;
import cn.bijy.pojo.SqlCommandType;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XMLMapperBuilder {
    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException, ClassNotFoundException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");
        List<Element> selectElements = rootElement.selectNodes("//select");
        setMapedStatementMap(namespace,selectElements,SqlCommandType.SELECT);

        List<Element> insertList = rootElement.selectNodes("//insert");
        setMapedStatementMap(namespace,insertList,SqlCommandType.INSERT);

        List<Element> updateList = rootElement.selectNodes("//update");
        setMapedStatementMap(namespace,updateList,SqlCommandType.UPDATE);
    }

    private void setMapedStatementMap(String namespace,List<Element> insertList,SqlCommandType sqlCommandType) throws ClassNotFoundException {
        for (Element selectElement : insertList) {
            String id = selectElement.attributeValue("id");
            String key = namespace+"."+id;
            String paramterType = selectElement.attributeValue("paramterType");
            Class<?> parameterTypeClass = null;
            if (paramterType !=null) {
                parameterTypeClass = getClassType(paramterType);
            }
            String resultType = selectElement.attributeValue("resultType");
            Class<?> resultTypeClass = getClassType(resultType);
            String textTrim = selectElement.getTextTrim();

            MapedStatement mapedStatement = new MapedStatement();
            mapedStatement.setId(id);
            mapedStatement.setSql(textTrim);
            mapedStatement.setParamterType(parameterTypeClass);
            mapedStatement.setResultType(resultTypeClass);
            mapedStatement.setSqlCommandType(sqlCommandType);
            configuration.getMapedStatementMap().put(key,mapedStatement);
        }
    }

    private Class<?> getClassType(String paramterType) throws ClassNotFoundException {
        return Class.forName(paramterType);
    }
}
